package com.egobuy.cms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.egobuy.cms.mapper.ContentCategoryMapper;
import com.egobuy.cms.service.IContentCategoryService;
import com.egobuy.entity.ContentCategory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.egobuy.pojo.BuyResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.geom.RectangularShape;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 内容分类 服务实现类
 * </p>
 *
 * @author 戴着假发的程序员
 * @since 2021-11-22
 */
@Service
public class ContentCategoryServiceImpl extends ServiceImpl<ContentCategoryMapper, ContentCategory> implements IContentCategoryService {
    @Autowired
    private ContentCategoryMapper contentCategoryMapper;
    @Override
    public BuyResult deleteCat(long id) {
        //父节点，没有叶子要改为0
        //...
        BuyResult result=BuyResult.ok();
        contentCategoryMapper.deleteById(id);
        return result;
    }

    @Override
    public BuyResult<ContentCategory> editCat(ContentCategory contentCategory) {

        BuyResult result=BuyResult.ok();

        contentCategoryMapper.updateById(contentCategory);
        result.setData(contentCategoryMapper.selectById(contentCategory.getId()));
        return result;
    }

    @Override
    public BuyResult<ContentCategory> saveCat(ContentCategory contentCategory) {
        BuyResult result=BuyResult.ok();
        Date date=new Date();
        contentCategory.setCreated(date);
        contentCategory.setUpdated(date);
        contentCategory.setSortOrder(1);
        contentCategory.setStatus(1);
        contentCategory.setIsParent(false);
        contentCategoryMapper.insert(contentCategory);

        result.setData(contentCategory);

        //将父节点改为 1
        if (contentCategory.getParentId()!=0){
            Long parentId = contentCategory.getParentId();
            //父节点更新
            ContentCategory cat=new ContentCategory();
            //根据id更新
            cat.setId(parentId);
            cat.setIsParent(true);
            contentCategoryMapper.updateById(cat);
        }

        //

        return result;
    }

    @Override
    public BuyResult<List<ContentCategory>> queryByParentId(long parentId) {
        BuyResult<List<ContentCategory>> result=BuyResult.ok();
        QueryWrapper<ContentCategory> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("parent_id",parentId);
        queryWrapper.eq("status",1);
        // 查询
        result.setData(contentCategoryMapper.selectList(queryWrapper));
        return result;
    }
}
